package com.xzjt.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xzjt.entity.SysUser;
import com.xzjt.exception.InvalidTokenException;
import com.xzjt.mapper.SysUserMapper;
import com.xzjt.service.AuthcService;
import com.xzjt.utils.JwtUtil;
import com.xzjt.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: AuthcServiceImpl
 * @Author: yuandong
 * @Date 2021/10/8 14:06
 */
@Service
public class AuthcServiceImpl implements AuthcService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public SysUser selectUserByName(String username) {
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        return sysUser;
    }


    /**
     * 验证token(UserRealm中)
     * @param token
     */
    @Override
    public void validateToken(String token)  {

        // 先校验缓存中Token是否存在，缓存中不存在Token说明Token已失效，需要重新登录
        String tokenInfo = stringRedisTemplate.opsForValue().get(token);
        if (StringUtils.isEmpty(tokenInfo)) {
            throw new InvalidTokenException();
        }

        //如果redis中存在token,需要验证token是否正确
        String username=JwtUtil.getUsername(token);
        if(StringUtils.isBlank(username)){
            throw new InvalidTokenException();
        }

        SysUser sysUser = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        if(sysUser==null){
            throw new InvalidTokenException();
        }
        //验证token是否正确
        if(!JwtUtil.verify(token,username)){
            throw new InvalidTokenException();
        }

        //更新token的有效期
        long tokenExpireTime = 60;
        JSONObject obj = new JSONObject();
        obj.put("sysUser", sysUser);
        stringRedisTemplate.expire(token, tokenExpireTime, TimeUnit.MINUTES);
    }
}
